<template>
  <div class="reset-form-container">
    <el-steps :active="step" finish-status="success" simple class="steps-bar">
      <el-step title="填写邮箱" />
      <el-step title="验证并重置" />
      <el-step title="完成" />
    </el-steps>

    <el-form v-if="step === 0" ref="emailFormRef" :model="emailForm" :rules="emailRules" label-width="90px" class="reset-form">
      <h2 class="form-title">找回密码</h2>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="emailForm.email" placeholder="请输入注册邮箱" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="next-btn" @click="toNextFromEmail" :disabled="sending">下一步</el-button>
      </el-form-item>
    </el-form>

    <el-form v-else-if="step === 1" ref="resetFormRef" :model="resetForm" :rules="resetRules" label-width="90px" class="reset-form">
      <h2 class="form-title">验证并重置</h2>
      <el-form-item label="邮箱">
        <el-input :model-value="emailForm.email" disabled />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="resetForm.code" placeholder="请输入验证码" />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="resetForm.password" type="password" show-password placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirm">
        <el-input v-model="resetForm.confirm" type="password" show-password placeholder="请再次输入新密码" />
      </el-form-item>
      <div class="form-actions">
        <el-button @click="step=0" :disabled="submitting">上一步</el-button>
        <el-button type="primary" class="next-btn" :loading="submitting" @click="onReset">提交</el-button>
      </div>
    </el-form>

    <div v-else-if="step === 2" class="result-panel">
      <h2 class="success-title">密码重置成功</h2>
      <p class="tip">现在可以前往登录。</p>
      <el-button type="primary" class="login-btn" @click="goLogin">去登录</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { sendVerificationCodeApi, validateCodeApi, resetPasswordApi } from '@/api/auth/register'
import { useRouter } from 'vue-router'

const router = useRouter()
const step = ref(0)

// Step 0
const emailFormRef = ref()
const emailForm = ref({ email: '' })
const emailRules = { email: [ { required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '邮箱格式不正确', trigger: ['blur','change'] } ] }
const sending = ref(false)
const countdown = ref(0)
let timer: number | null = null

const onSendCode = async () => {
  if (!emailFormRef.value) return
  try {
    await (emailFormRef.value as any).validateField('email')
  } catch { return }
  sending.value = true
  try {
  await sendVerificationCodeApi({ email: emailForm.value.email, purpose: 'reset_password' })
    ElMessage.success('验证码已发送')
  // 发送成功后立即进入下一步（验证码 + 重置）
  step.value = 1
    countdown.value = 60
    timer && clearInterval(timer)
    timer = window.setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        timer && clearInterval(timer)
        countdown.value = 0
      }
    }, 1000)
  } catch (e:any) {
    ElMessage.error(e?.message || '发送失败')
  } finally {
    sending.value = false
  }
}

const toNextFromEmail = async () => {
  try {
    await (emailFormRef.value as any).validateField('email')
  } catch { return }
  if (sending.value) return
  await onSendCode()
}

// Step 1
const resetFormRef = ref()
const resetForm = ref({ code: '', password: '', confirm: '' })
const resetRules = {
  code: [ { required: true, message: '请输入验证码', trigger: 'blur' } ],
  password: [ { required: true, message: '请输入新密码', trigger: 'blur' }, { min: 6, max: 20, message: '长度 6-20 位', trigger: 'blur' } ],
  confirm: [ { required: true, message: '请确认密码', trigger: 'blur' }, { validator: (r:any,v:string,cb:any)=> { if (v !== resetForm.value.password) cb(new Error('两次密码不一致')); else cb() }, trigger: 'blur' } ]
}
const submitting = ref(false)

const onReset = async () => {
  if (!resetFormRef.value) return
  try {
    await (resetFormRef.value as any).validate()
  } catch { return }
  submitting.value = true
  try {
    await resetPasswordApi({ email: emailForm.value.email, verificationCode: resetForm.value.code, newPassword: resetForm.value.password })
    ElMessage.success('密码重置成功')
    step.value = 2
  } catch(e:any) {
    ElMessage.error(e?.message || '重置失败')
  } finally { submitting.value = false }
}

const goLogin = () => router.push('/login')
</script>

<style scoped>
.reset-form-container { max-width: 520px; margin: 60px auto; background:#fff; border-radius:16px; box-shadow:0 4px 28px rgba(25,118,210,.12); padding:40px 40px 32px; border:1px solid #e6f0fa; }
.steps-bar { margin-bottom: 28px; }
.reset-form { --el-color-primary:#1976d2; }
.form-title { margin:0 0 18px; font-size:22px; font-weight:600; text-align:center; background:linear-gradient(90deg,#1976d2,#42a5f5); background-clip:text; -webkit-background-clip:text; color:transparent; }
.send-btn, .next-btn, .login-btn { background:linear-gradient(90deg,#1976d2,#42a5f5); border:none; color:#fff; font-weight:600; letter-spacing:.5px; }
.send-btn:disabled { filter:grayscale(.4); opacity:.8; }
.form-actions { display:flex; justify-content:space-between; gap:12px; margin-top:4px; }
.result-panel { text-align:center; padding:40px 10px; }
.success-title { font-size:24px; font-weight:600; background:linear-gradient(90deg,#1976d2,#42a5f5); background-clip:text; -webkit-background-clip:text; color:transparent; margin:0 0 12px; }
.tip { color:#5f6b7a; margin-bottom:24px; }
.login-btn { width:200px; }
</style>
